package com.doubledragon.tiny.context;

import com.doubledragon.tiny.aop.autoProxyCreator.BeanPostProcessor;
import com.doubledragon.tiny.ioc.BeanDefinition;
import com.doubledragon.tiny.ioc.factory.AbstractBeanFactory;
import com.doubledragon.tiny.ioc.factory.AutowireCapableBeanFactory;
import com.doubledragon.tiny.ioc.io.ResourceLoad;
import com.doubledragon.tiny.ioc.xmlReader.impl.XmlBeanDefinitionReader;

import java.util.List;
import java.util.Map;

/**
 * Created by dragon
 *
 * 实现xml读取DeanDefinition的方法
 */
public class ClassPathXmlApplicationContext extends AbstractApplicationContext {

    private String configLocation;

    public ClassPathXmlApplicationContext(String configLocation) throws Exception {
        this(configLocation, new AutowireCapableBeanFactory());
    }


    public ClassPathXmlApplicationContext(String configLocation, AbstractBeanFactory beanFactory) throws Exception {
        super(beanFactory);
        this.configLocation = configLocation;
        //调用父类的refresh方法，进行BeanFactory的创建和扩展，BeanDefinition的创建和注册
        refresh();
    }

    @Override
    public void loadBeanDefinition() throws Exception {
        XmlBeanDefinitionReader xmlBeanDefinitionReader = new XmlBeanDefinitionReader(new ResourceLoad());
        xmlBeanDefinitionReader.loadBeanDefinition(this.configLocation);
        Map<String, BeanDefinition> registry = xmlBeanDefinitionReader.getRegistry();
        for (Map.Entry<String, BeanDefinition> entry : registry.entrySet()) {
            beanFactory.registerBeanDefinition(entry.getKey(), entry.getValue());
        }
    }

    @Override
    protected void registryBeanPostProccesser() throws Exception {
        List beanPostProcesser = beanFactory.getBeanByType(BeanPostProcessor.class);
        beanFactory.getBeanPostProcessors().addAll(beanPostProcesser);
    }
}
